import {Image, Text, View} from "@tarojs/components";
import {RoundNum} from '@/utils/helper'
import { AtModal } from "taro-ui";
import {useEffect, useState,useMemo,useRef} from "react";
import Taro from "@tarojs/taro";
import YiCode from '@/components/yi-code'
import ActivityModal from "../confirmOrder/activityModal";
import './index.scss'

export default () => {
  const {router} = Taro.getCurrentInstance()
  const couponRef = useRef({})
  const [selectGoodsCoupon,setSelectGoodsCoupon] = useState([])
  const [info,setInfo] = useState({})
  const [goodsList,setGoodsList] = useState([])
  const [curCard,setCurCard] = useState({})
  const [showModal,setShowModal] = useState(false)
  const [showActivity,setShowActicity] = useState(false)
  const [captcha, setCaptcha] = useState('')
  const [messageInfo, setMessageInfo] = useState('')
  const [priceMap,setPriceMap]=useState({
    totalPrice:0
  })
  useEffect(() => {
    Taro.$get('/cinema-app/api/v1/order', {
      orderId: router.params.id
    }).then(res=>{
      if (res.code == '1') {
        setInfo(res.content)
        setGoodsList(res.content.goodsViewList)
        setPriceMap({
          totalPrice:res.content.payAmount
        })
      }else{
        Taro.$toast(res.message || '提交失败')
      }
    })
    Taro.eventCenter.off('changeCoupon')
    Taro.eventCenter.on('changeCoupon', async (data)=>{
      if(data.goods){
        couponRef.current = {...couponRef.current,goods:data.goods}
        setSelectGoodsCoupon(data.goods)
      }
      const res = await handleCalcPrice(data)
      if(res.code == '1'){
        setPriceMap({
          totalPrice: res.content.payAmount
        })
      }else{
        setTimeout(() => {
          Taro.$toast(res.message || '提交失败')
        }, 500);
        couponRef.current = {...couponRef.current,goods:[]}
        setSelectGoodsCoupon([])
      }
    })
    Taro.eventCenter.off('changeCard')
    Taro.eventCenter.on('changeCard', async (data)=>{
      if(data.curCard){
        setCurCard(data.curCard)
        if(data.curCard.isDxCard == '1'){
          data.goods = []
          couponRef.current = {...couponRef.current,goods:[]}
          setSelectGoodsCoupon([])
        }
      }else{
        setCurCard({})
      }
      const res = await handleCalcPrice(data)
      if(res.code == '1'){
        setPriceMap({
          totalPrice: res.content.payAmount,
        })
      }else{
        setCurCard({})
        setTimeout(() => {
          Taro.$toast(res.message || '提交失败')
        }, 500);
      }
    })
  }, []);

  let calcNum = useMemo(()=>{
    let num = 0;
    goodsList.map(res=>{
      num += res.goodsCount
    })
    return num || 0
  },[goodsList])

  async function handleCalcPrice(values){  ///  锁定优惠券计算价格
    let goodsCoupon = values?.goods || couponRef.current.goods
    let selectCard = values?.curCard || curCard
    const data = {
      orderId: router.params.id,
      cinemaId:Taro.getStorageSync('merchantId'),
      goodsCouponIdList:[]
    }
    if(goodsCoupon?.length){
      goodsCoupon.map(res=>{
        data.goodsCouponIdList.push(res.id)
      })
    }
    if(selectCard.id){
      data.memberCardNo = selectCard.id
    }
    Taro.showLoading({title:'加载中...'})
    return await Taro.$post('/cinema-app/api/v1/order/pricing',data,'1')
  }
  const pay =e=>{
    const data = {
      orderId: Taro.getCurrentInstance()?.router?.params?.id,
      cinemaGovCode:Taro.getStorageSync('selectMerchant').cinemaGovCode,
      cinemaId:Taro.getStorageSync('merchantId'),
      goodsCouponIdList:[]
    }
    if(couponRef.current.goods?.length){
      couponRef.current.goods.map(res=>{
        data.goodsCouponIdList.push(res.id)
      })
    }
    if(curCard.id){
      data.memberCardNo = curCard.id,
      data.cardPassword = captcha
    }
    Taro.showLoading({title:'加载中...'})
    Taro.$post('/cinema-app/api/v1/order/push',data, '1').then(res => {
      if (res.code != '1') {
        Taro.$toast(res.message)
        return
      }
      if(curCard.id && curCard.isDxCard == '1'){
        Taro.redirectTo({
          url: `/orderSubPack/pay-status/index?id=${res.content.orderId}`
        })
        return;
      }
      if (res.content?.needPay) {
        Taro.navigateTo({
          url: `/pages/fineEngine/payment?id=${res.content.orderId}`
        })
      } else {
        Taro.redirectTo({
          url: `/orderSubPack/pay-status/index?id=${res.content.orderId}`
        })
      }
    })
  }
  return (
    <View className='page'>
      <View className='page-content'>
        <View className='part-5'>
          <View className='row-1'>观影伴侣·美味小食</View>
          <View className='row-2'>
            <View className='item'>
              {goodsList.map(goods => {
                return (
                  <View className='item' key={goods.id}>
                    <View className='goods-item flex-cc'>
                      <Image className='c-1' src={goods.imageUrl}></Image>
                      <View className='c-2'>
                        <View className='r-1'>{goods.goodsName}</View>
                        <View className='r-1-1 dot2'>{goods.goodsDesc}</View>
                        <View className='r-2'>
                          <View className='i-1'>
                            <Text>￥</Text>
                            <Text className='i-1-1'>{goods.goodsPrice}</Text>
                          </View>
                          <Text className="item-num">x{goods.goodsCount}</Text>
                        </View>
                      </View>
                    </View>
                  </View>
                )
              })}
            </View>
          </View>
          <View className='row-3 flex-cc'>
            <Text style={{marginRight:5,marginLeft:'auto'}}>共{calcNum}件</Text>
            <Text>小食总计：¥{info.payAmount}</Text>
          </View>
          
          <View className='list-item'>
            <View className='item-label'>优惠券</View>
            <View className='c-2' onClick={()=>{
              Taro.navigateTo({
                url:`/mainPages/select-coupon/index?id=${info.id}&type=goods`
              })
            }}>
              {selectGoodsCoupon.length?<Text className='i-3 dot'>{selectGoodsCoupon.length>1?'多券叠加':selectGoodsCoupon[0]?.voucherName}</Text>:<Text className='i-2'>未使用</Text>}
              <Text className="at-icon at-icon-chevron-right"></Text>
            </View>
          </View>
          <View className='list-item'>
            <View className='item-label'>会员权益</View>
            <View className='c-2'>
              <Text className='i-2'>未使用</Text>
              <Text className="at-icon at-icon-chevron-right"></Text>
            </View>
          </View>
        </View>
        <ActivityModal showActivity={showActivity} onClose={()=>{setShowActicity(false)}} />
        <View className='part-3'>
          <View className='row-1'>支付方式</View>
          <View className='item'>
            <View className='c-1'>电影卡支付</View>
            <View className='c-2' onClick={()=>{
              Taro.navigateTo({
                url:`/mainPages/select-card/index?id=${info.id}&cardId=${curCard.id}`
              })
            }}>
              {curCard?.id?<Text>{curCard.cardName}</Text>:<Text className='i-1'>未使用</Text>}
              <Text className="at-icon at-icon-chevron-right"></Text>
            </View>
          </View>
          {curCard?.id?<View className="item-p">
            <View>余额：¥{curCard.amount}</View>
            <View>消费余额：¥{RoundNum(priceMap.totalPrice)}</View>
          </View>:null}
          <View className='item'>
            <View className='c-1'>{process.env.TARO_ENV == 'tt'?'抖音支付':'微信支付'}</View>
            <View className='c-2'>
              <Image className='i-2' src={require('@/images/mine/radio-on.svg')}></Image>
            </View>
          </View>
        </View>
      </View>
      <View className='bottom flex-cc'>
        <View className='col-2 flex-cc' onClick={()=>{
          if(curCard?.id){
            setShowModal(true)
            return;
          }
          pay()
        }}>立即支付 ¥{priceMap.totalPrice}</View>
      </View>
      <AtModal className="order-modal" isOpened={showModal} onClose={()=>{setShowModal(false)}}>
        {showModal?<>
        <View className="modal-header">
          <View className='at-icon at-icon-close' onClick={()=>{setShowModal(false)}}></View>
          <View className="header-h2">验证卡密码</View>
          <View></View>
        </View>
        <View className="modal-main">
          <View className="main-span" style={{marginBottom:'24px'}}>为了保证你的账号安全，请输入您的会员卡密码后进行下一步操作。</View>
          <YiCode isFocus={showModal} inputType='password' value={captcha} onConfirm={(code) => {
            setCaptcha(code)
          }} />
          {messageInfo?<View className="main-info"><Text style={{marginRight:'4px'}} className='at-icon at-icon-alert-circle'></Text>{messageInfo}</View>:null}
        </View>
        <View className="modal-footer">
          <View className="footer-go" onClick={()=>{
            if(captcha.trim()){
              const data = {
                cardId: curCard.id,
                password: captcha,
                type:curCard.isDxCard
              }
              Taro.$post('/cinema-app/api/card/checkPassword',data,'1').then(res=>{
                if(res.code == '1' && res.content){
                  pay()
                }else{
                  setMessageInfo('密码错误')
                  setCaptcha('')
                }
              })
            }
          }}>确认支付</View>
        </View>
        </>:null}
      </AtModal>
    </View>
  )
}
